<?php
/**
 * Created by PhpStorm.
 * Author: sitewang@aliyun.com
 * CreateTime: 2022/4/6 5:46 PM
 * Blog：www.myblogs.xyz
 */

namespace App\Http\Controllers\Admin;

use App\Models\User;
use App\Services\CommonService;
use Illuminate\Http\Request;

class UserController extends CommonController
{
    public function index()
    {
        $user_model = new User();
        $user_model->fields = ['password', true];
        $user_list = $user_model->userLists('', 10, 'create_time desc');
        return view('admin/user', compact('user_list'));
    }

    public function insert()
    {
        $this->getData();
        return view('admin.save_user');
    }

    public function update()
    {
        $this->getData();
        return view('admin.save_user');
    }

    protected function getData()
    {
        $user_id = request('user_id', 0);
        $oldData = [];
        if (!empty($user_id)){
            $user_model = new User();
            $oldData = $user_model->getFind($user_id);
        }
        view()->share('oldData', $oldData);
    }

    public function save(Request $request)
    {
        $data = $request->post();
        if (!empty($data)){
            $user_model = new User();
            unset($data['_token']);;
            if (empty($data[$user_model->getPrimaryKey()])){
                if (empty($data['password'])){
                    $this->returnError('请填写账户密码');
                }
                $data['account'] = $user_model->getAccount();
                $data['create_time'] = NEW_TIME;
            }else{
                $data['update_time'] = NEW_TIME;
            }
            if (!empty($data['password'])){
                $data['password'] = md5($data['password']);
            }
            $rows = $user_model->operation($data);
            if (!$rows){
                $this->returnError($user_model->getError());
            }
            $this->returnSuccess('保存成功', url('admin/user'), 'on');
        }
    }

    public function audit()
    {
        if (CommonService::audit('status', 1, 0,new User())){
            $this->returnSuccess('操作成功', url('admin/article'));
        }
        $this->returnError('操作失败');
    }

    public function delete()
    {
        if (CommonService::delete(new User())){
            $this->returnSuccess('删除成功', url('admin/article'));
        }
        $this->returnError('删除失败');
    }
}
